package regist;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.FIFOCache;
import regist.aliutil.Config;


public class AliDeviceRegist {
		
	private static Logger logger = LoggerFactory.getLogger(AliDeviceRegist.class);
	public static FIFOCache<String, Object> cacheDevice = CacheUtil.newFIFOCache(1000, 3600 * 1000);
	
	 
    /**
     * 动态注册。
     *
     * @param deviceName 设备名称
     * @throws Exception
     */
    public boolean register(String deviceName) throws Exception {
        // 表示客户端ID，建议使用设备的MAC地址或SN码，64字符内。
    	String productKey = PropertyConfig.getStr("productKey");
    	String broker  = "ssl://" + productKey + ".iot-as-mqtt." + PropertyConfig.getStr("regionId") + ".aliyuncs.com:443";;
    	String productSecret = PropertyConfig.getStr("productSecret");
        String clientId = productKey + "." + deviceName;

        // 获取随机值。
        Random r = new Random();
        int random = r.nextInt(1000);
        // securemode只能为2表示只能使用TLS；signmethod指定签名算法。
        String clientOpts = "|securemode=2,authType=regnwl,signmethod=" + Config.HMAC_ALGORITHM + ",random=" 
        		+ random +"|";
        if(StringUtils.isNotEmpty(PropertyConfig.getStr("instanceId"))){
        	clientOpts = "|securemode=2,authType=regnwl,signmethod=" + Config.HMAC_ALGORITHM + ",random=" 
            		+ random + ",instanceId="+PropertyConfig.getStr("instanceId")+"|";
        }

        // MQTT接入客户端ID。
        String mqttClientId = clientId + clientOpts;

        // MQTT接入用户名。
        String mqttUsername = deviceName + "&" + productKey;

        // MQTT接入密码，即签名。
        JSONObject params = new JSONObject();
        params.put("productKey", productKey);
        params.put("deviceName", deviceName);
        params.put("random", random);
        String mqttPassword = sign(params, productSecret);
        // 通过MQTT connect报文进行动态注册。
        return connect(broker, mqttClientId, mqttUsername, mqttPassword);
    }

    /**
     * 通过MQTT connect报文发送动态注册信息。
     *
     * @param serverURL 动态注册域名地址
     * @param clientId 客户端ID
     * @param username MQTT用户名
     * @param password MQTT密码
     */
    @SuppressWarnings("resource")
    private boolean connect(String serverURL, String clientId, final String username, String password) {
    	MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(false);
        connOpts.setKeepAliveInterval(60*4);
        connOpts.setMqttVersion(4);// MQTT 3.1.1
        connOpts.setUserName(username);// 用户名
        connOpts.setPassword(password.toCharArray());// 密码
        connOpts.setAutomaticReconnect(false); // MQTT动态注册协议规定必须关闭自动重连。
        System.out.println("----- register params -----");
        System.out.print("server=" + serverURL + ",clientId=" + clientId);
        System.out.println(",username=" + username + ",password=" + password);
    	try {
           // MemoryPersistence persistence = new MemoryPersistence();
            final MqttClient sampleClient = new MqttClient(serverURL, clientId);
            sampleClient.setCallback(new MqttCallback() {
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // 仅处理动态注册返回消息。
                    if (Config.REGISTER_TOPIC.equals(topic)) {
                        String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
                        System.out.println("----- register result -----");
                        System.out.println(payload);
                        JSONObject regist_info = JSONObject.parseObject(payload);
                        JSONObject conn_info = new JSONObject();
                        conn_info.put("address",PropertyConfig.getStr("productKey")+Config.MQTT_ADDRESS_SUFF);
                        conn_info.put("port",Config.MQTT_PORT);
                        conn_info.put("productKey", PropertyConfig.getStr("productKey"));
                        conn_info.put("clientId",regist_info.getString("clientId")+Config.MQTT_CLIENT_NWL_SUFF);
                        conn_info.put("userName", username);
                        conn_info.put("password", regist_info.getString("deviceToken"));
                        cacheDevice.put(regist_info.getString("deviceName"), conn_info.toString());
                    }
                    sampleClient.disconnect();
                    sampleClient.close();
                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                }

                public void connectionLost(Throwable cause) {
                }
            });
            sampleClient.connect(connOpts);
            return true;
        } catch (MqttException e) {
            System.out.println("excep " + e);
            logger.error("物联网平台mqtt注册失败",e);
            return false;
        }
    }

    /**
     * 动态注册签名。
     *
     * @param params 签名参数
     * @param productSecret 产品密钥
     * @return 签名十六进制字符串
     */
    private String sign(JSONObject params, String productSecret) {

        // 请求参数按字典顺序排序。
        Set<String> keys = getSortedKeys(params);

        // sign、signMethod除外。
        keys.remove("sign");
        keys.remove("signMethod");

        // 组装签名明文。
        StringBuffer content = new StringBuffer();
        for (String key : keys) {
            content.append(key);
            content.append(params.getString(key));
        }

        // 计算签名。
        String sign = encrypt(content.toString(), productSecret);
        System.out.println("sign content=" + content);
        System.out.println("sign result=" + sign);

        return sign;
    }

    /**
     * 获取JSON对象排序后的key集合。
     *
     * @param json 需要排序的JSON对象
     * @return 排序后的key集合
     */
    private Set<String> getSortedKeys(JSONObject json) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        for (String key : json.keySet()) {
            String vlaue = json.getString(key);
            map.put(key, vlaue);
        }
        return map.keySet();
    }

    /**
     * 使用HMAC_ALGORITHM加密。
     *
     * @param content 明文
     * @param secret 密钥
     * @return 密文
     */
    private String encrypt(String content, String secret) {
        try {
            byte[] text = content.getBytes(StandardCharsets.UTF_8);
            byte[] key = secret.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(key, Config.HMAC_ALGORITHM);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return byte2hex(mac.doFinal(text));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("注册签名失败",e);
            return null;
        }
    }

    /**
     * 二进制转十六进制字符串。
     *
     * @param b 二进制数组
     * @return 十六进制字符串
     */
    private String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int n = 0; b != null && n < b.length; n++) {
            String stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append('0');
            }
            sb.append(stmp);
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) throws Exception {
    	AliDeviceRegist regist = new AliDeviceRegist();
    	regist.register("12357");
	}
}
